﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.Utils;
using FlyHorse.LIMS.WinApp.XtraReportTemplate;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;
using DevExpress.XtraGrid;
using FlyHorse.LIMS.WinApp.LanguageResource;
using FlyHorse.LIMS.WinApp.Model;
using DevExpress.XtraPrinting;
using System.Drawing.Printing;

namespace FlyHorse.LIMS.WinApp.DataManageForms.ReportRawForms
{
    public partial class ReportRawMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.ReportRawBll reportRawBll = new BLL.ReportRawBll();
        BLL.GoodBll goodsBll = new BLL.GoodBll();
        BLL.ToolBll toolBll = new BLL.ToolBll();
        IQueryable<ReportRaw> _models;
        public ReportRawMainForm()
        {
            InitializeComponent();
        }

        private void ReportRawMainForm_Load(object sender, EventArgs e)
        {
            CheckAuthority();

            this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView1.OptionsBehavior.Editable = false;
            this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;

            var goodsList = goodsBll.GetRawGoodList();
            searchLookUpEdit_Goods.Properties.DataSource = goodsBll.GetRawGoodList();
            repositoryItemLookUpEdit1.DataSource = goodsBll.LoadEntities(m => true).ToList();
            repositoryItemLookUpEdit2.DataSource = toolBll.GetAllLoginUersList();
            repositoryItemLookUpEdit3.DataSource = toolBll.GetTestItemList();


            var models = reportRawBll.LoadEntitiesAsNoTracking(m => true).OrderByDescending(m => m.SendDate).ThenByDescending(m => m.AddDateTime);
            _models = models;
            InitGrid(_models);

            gridView2.BeginDataUpdate();
            try
            {
                gridView2.ClearSorting();
                gridView2.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            }
            finally
            {
                gridView2.EndDataUpdate();
            }
        }

        private void ButtonItem_Add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReportRawDetailForm reportRawDetailForm = new ReportRawDetailForm(RefreshGrid);
            reportRawDetailForm.ShowDialog();

        }


        private void simpleButton_search_Click(object sender, EventArgs e)
        {
            var models = reportRawBll.LoadEntitiesAsNoTracking(m => true);

            if (searchLookUpEdit_Goods.EditValue != null)
            {
                string goodsID = Convert.ToString(searchLookUpEdit_Goods.EditValue);
                models = models.Where(m => m.GoodsID == goodsID);
            }

            if (dateEdit_SendDateStart.EditValue != null)
            {
                models = models.Where(m => m.SendDate >= dateEdit_SendDateStart.DateTime);
            }
            if (dateEdit_SendDateEnd.EditValue != null)
            {
                models = models.Where(m => m.SendDate <= dateEdit_SendDateEnd.DateTime);
            }
            if (textEdit_SampleNO.Text != "")
            {
                models = models.Where(m => m.SampleNO.Contains(textEdit_SampleNO.Text));
            }
            if (textEdit_ProductUnit.Text != "")
            {
                models = models.Where(m => m.ProductionUnit.Contains(this.textEdit_ProductUnit.Text));
            }
            _models = models;
            InitGrid(_models);
        }




        private void InitGrid(IQueryable<ReportRaw> models)
        {
            models = models.OrderByDescending(m => m.AddDateTime).ThenByDescending(m=>m.SampleNO);
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int pageSize = 0;
            try
            {
                pageSize = Convert.ToInt32(this.barEditItem_pageSize.EditValue);
            }
            catch (Exception)
            {
                XtraMessageBox.Show(ResourceOverall.TotalPageErr);
                return;
            }
            if (pageSize == 0)
            {
                barEditItem_pageSize.EditValue = 30;
                pageSize = 30;
            }


            splashScreenManager1.ShowWaitForm();
            //...?
            PagedList<ReportRaw> pagedList = new PagedList<ReportRaw>(models, pageIndex, pageSize);
            this.barStaticItem_pageIndex.Caption = pagedList.PageIndex.ToString();
            this.barStaticItem_totalPage.Caption = pagedList.TotalPages.ToString();
            this.barEditItem_pageSize.Caption = pagedList.PageSize.ToString();
            List<ReportRawModel> reportList = TransformReport.TransformRawReport(pagedList);
            this.gridControl1.DataSource = reportList;

            splashScreenManager1.CloseWaitForm();
            //gridView2.BeginDataUpdate();
            //try
            //{
            //    gridView2.Columns["FormOrder"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            //}
            //finally
            //{
            //    gridView2.EndDataUpdate();
            //}

        }

        private void ButtonItem_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportRawID") != null)
            {
                EditEntity();
            }
        }

        private void EditEntity()
        {
            string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportRawID"));
            ReportRaw report = reportRawBll.LoadEntities(m => m.ReportRawID == id).FirstOrDefault();
            if (report != null)
            {
                ReportRawDetailForm detailForm = new ReportRawDetailForm(report, RefreshGrid);
                detailForm.ShowDialog();
            }
        }





        private void ButtonItem_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (this.gridView1.GetFocusedRowCellValue("ReportRawID") != null)
            {
                string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportRawID"));
                ReportRaw report = reportRawBll.LoadEntities(m => m.ReportRawID == id).FirstOrDefault();
                if (report != null)
                {
                    DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {
                        bool res = reportRawBll.DeleteRawReportAndRestult(report);
                        if (res)
                        {
                            InitGrid(_models);
                            XtraMessageBox.Show(ResourceOverall.DeleteSucceed);
                        }
                    }
                }
            }
        }

        private void ButtonItem_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("ReportRawID"));
            ReportRaw reportRaw = reportRawBll.LoadEntities(m => m.ReportRawID == id).First();
            XtraReportRaw report = new XtraReportRaw(reportRaw);
            using (ReportPrintTool printTool = new ReportPrintTool(report))
            {
                // Invoke the Ribbon Print Preview form modally, 
                // and load the report document into it.
                printTool.ShowRibbonPreviewDialog();

                // Invoke the Ribbon Print Preview form
                // with the specified look and feel setting.
                printTool.ShowRibbonPreview(UserLookAndFeel.Default);
            }
        }
        private void barEditItem_pageSize_EditValueChanged(object sender, EventArgs e)
        {
            InitGrid(_models);
        }


        private void barButton_firstPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.barStaticItem_pageIndex.Caption = "1";
            InitGrid(_models);
        }

        private void barButton_previousPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            if (pageIndex >= 1)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex - 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_nextPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = (pageIndex + 1).ToString();
                InitGrid(_models);
            }
        }

        private void barButton_lastPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int pageIndex = Convert.ToInt32(this.barStaticItem_pageIndex.Caption);
            int totalPage = Convert.ToInt32(barStaticItem_totalPage.Caption);
            if (pageIndex < totalPage)
            {
                this.barStaticItem_pageIndex.Caption = totalPage.ToString();
                InitGrid(_models);
            }
        }

        private void simpleButton_clear_Click(object sender, EventArgs e)
        {
            ShowAllData();
        }

        private void ShowAllData()
        {
            this.searchLookUpEdit_Goods.EditValue = null;
            dateEdit_SendDateStart.EditValue = null;
            textEdit_SampleNO.Text = "";
            textEdit_ProductUnit.Text = "";

            var models = reportRawBll.LoadEntities(m => true);
            _models = models;
            InitGrid(_models);
        }


        private void CheckAuthority()
        {
            List<Resource> resList = LoginUserUtil.LoginUser.Role.Resources.ToList();

            if (resList.Where(m => m.ResourceKey == "RawReportButtonItem_Add").Count() != 1)
            {
                ButtonItem_Add.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "RawReportButtonItem_Edit").Count() != 1)
            {
                ButtonItem_Edit.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "RawReportButtonItem_Delete").Count() != 1)
            {
                ButtonItem_Delete.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "RawReportButtonItem_Print").Count() != 1)
            {
                ButtonItem_Print.Enabled = false;
            }
            if (resList.Where(m => m.ResourceKey == "RawReportButtonItem_PrintAll").Count() != 1)
            {
                ButtonItem_PrintAll.Enabled = false;
            }
        }

        private void RefreshGrid()
        {
            InitGrid(_models);
        }


        

        private void ButtonItem_PrintAll_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            PreviewPrintableComponent(gridControl1, gridControl1.LookAndFeel);
        }

        private void PreviewPrintableComponent(IPrintable component, UserLookAndFeel lookAndFeel)
        {
            // Create a link that will print a control.?
            PrintableComponentLink link = new PrintableComponentLink()
            {
                PrintingSystemBase = new PrintingSystemBase(),
                Component = component,
                Landscape = true,
                PaperKind = PaperKind.A4,
                //Margins = new Margins(20, 20, 20, 20)
            };
            // Show the report.?
            link.ShowRibbonPreview(lookAndFeel);
        }

        //private void ShowGridPreview(GridControl grid)
        //{
        //    // Check whether the GridControl can be previewed.
        //    if (!grid.IsPrintingAvailable)
        //    {
        //        MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
        //        return;
        //    }

        //    // Open the Preview window.
        //    grid.ShowPrintPreview();
        //}

        //private void PrintGrid(GridControl grid)
        //{
        //    // Check whether the GridControl can be printed.
        //    if (!grid.IsPrintingAvailable)
        //    {
        //        MessageBox.Show("The 'DevExpress.XtraPrinting' library is not found", "Error");
        //        return;
        //    }

        //    // Print.
        //    grid.Print();
        //}

        //private void gridView1_PrintInitialize(object sender, DevExpress.XtraGrid.Views.Base.PrintInitializeEventArgs e)
        //{
        //    PrintingSystemBase pb = e.PrintingSystem as PrintingSystemBase;
        //    pb.PageSettings.Landscape = true;
        //    pb.PageSettings.PaperKind = PaperKind.A4;
        //}





    }
}